package com.ruoyi.framework.interceptor.impl;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.BaseEntityDraft;
import com.ruoyi.common.core.domain.BaseEntityProps;
import com.ruoyi.system.service.ISysUserService;
import org.babyfish.jimmer.ImmutableObjects;
import org.babyfish.jimmer.sql.DraftInterceptor;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class BaseEntityDraftInterceptor implements DraftInterceptor<BaseEntity, BaseEntityDraft> {

    private final ISysUserService userService;

    public BaseEntityDraftInterceptor(ISysUserService userService) {
        this.userService = userService;
    }

    @Override
    public void beforeSave(BaseEntityDraft draft, @Nullable BaseEntity original) {
        if (!ImmutableObjects.isLoaded(draft, BaseEntityProps.UPDATE_TIME)) {
            draft.setUpdateTime(LocalDateTime.now());
        }
        if (!ImmutableObjects.isLoaded(draft, BaseEntityProps.UPDATE_BY)) {
            draft.applyUpdateBy(user -> user.setUserId(userService.getCurrentUserId()));
        }
        if (original == null) {
            if (!ImmutableObjects.isLoaded(draft, BaseEntityProps.CREATE_TIME)) {
                draft.setCreateTime(LocalDateTime.now());
            }
            if (!ImmutableObjects.isLoaded(draft, BaseEntityProps.CREATE_BY)) {
                draft.applyCreateBy(user -> user.setUserId(userService.getCurrentUserId()));
            }
        }
    }
}